package com.ruoyi.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.pojo.User;
import com.ruoyi.service.UserService;
import com.ruoyi.until.R;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author: liufei
 * @Desc:
 * @create: 2024-10-21 09:08
 **/
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/login")
    public R login(@RequestBody User user){

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,user.getUsername());
        //判断用户名是否存在
        User userDb = userService.getOne(wrapper);
        if(ObjectUtils.isEmpty(userDb)){
            return R.error("用户名不存在");
        }
        //判断密码是否正确
        if(!userDb.getPassword().equals(user.getPassword())){
            return R.error("密码错误");
        }
        //登录人id通过jwts存入token
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "bwie").claim("role", userDb.getRole()).claim("username", userDb.getUsername()).claim("userId", userDb.getId()).compact();
        //token存入redis
        redisTemplate.opsForValue().set("token:"+userDb.getId(),token);

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("token",token);
        hashMap.put("role",userDb.getRole());
        hashMap.put("username",userDb.getUsername());

        return R.ok(token);
    }



}
